﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;

using Utils;
using Utils.Buffer;

namespace Microsoft.AspNetCore.Mvc
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
    public partial class AuthAttribute : Attribute
    {

        protected AuthAttribute(bool isValidate)
        {
            this.IsValidate = isValidate;
            UserTokenTypes = new Type[0];
        }

        public AuthAttribute(params Type[] userTokens) : this(true)
        {
            UserTokenTypes = userTokens;
        }

        public AuthAttribute(Type userToken, string rightCode) : this(userToken)
        {
            this.RightCode = rightCode;

        }

        public bool IsValidate { get; set; }

        public Type[] UserTokenTypes { get; set; }

        public string RightCode { get; set; }
        /// <summary>
        ///  
        /// </summary>
        /// <param name="context"></param>
        /// <param name="serviceProvider">请求周期</param>
        public virtual void OnAuthorization(AuthorizationFilterContext context)
        {
            try
            {
                if (!IsValidate)
                {
                    return;
                }
                var baseToken = context.HttpContext.Request.CreateByToken(UserTokenTypes.Any(a => a.Equals(typeof(AnonymousToken))));
                if (!baseToken.Is(UserTokenTypes))
                {
                    throw Error.CustomError(ErrorType.AuthorizationError, "票据不被允许");
                }
                if (!baseToken.Verify(RightCode))
                {
                    throw Error.CustomError(ErrorType.NoPermissionError, "无访问权限");
                }
                context.HttpContext.User = new ClaimsPrincipal(baseToken);
            }
            catch (CustomException e)
            {
                context.Result = new ObjectResult(Result.Fail(e.Message, e.Code));
            }
            catch (Exception e)
            {
                context.Result = new ObjectResult(Result.Fail(e.Message, ErrorType.AuthorizationError));
            }
        }








    }

}
